import pyshark
from SignalHandler import HeidelbergHandler
from datetime import datetime
import configparser
import atexit
import subprocess
import shlex
import time


class SignalClass:
    def __init__(self, name, capture_cls, handler_cls):
        self.name = name
        # self.history = History(self.name)
        self.capture = capture_cls
        self.handler = handler_cls
        self.start_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        self.total_count = 0
        self._print_count = 0
        # 退出时的存储动作
        atexit.register(self.save_on_exit)

    def run(self):
        for packet in self.capture:
            result = self.handler.handle(packet)
            if result["flag"] is True:
                # self.history.append(result["data"]) if result['data'] else None
                print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}: {result}") if result['data'] else None
            self._print_count = self.handler.print_count
            now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            print(f"{now}: Printed {self._print_count} pics since {self.start_time}")
            print(f"{now}: Total count: {self.total_count + self._print_count}")

    def save_on_exit(self):
        config2 = configparser.ConfigParser()
        config2.read("configure.ini")
        config2["Status"] = {"TotalCount": f"{self.total_count + self._print_count}"}
        with open('configure.ini', 'w') as configfile:
            config2.write(configfile)

    def signal_handler(self, signum, frame=None):
        self.save_on_exit()
        # sys.exit(1)


class Tcpdump(SignalClass):
    def __init__(self, name, capture_cls, handler_cls):
        super().__init__(name, capture_cls, handler_cls)
        self.process = subprocess.Popen(
            shlex.split("tcpdump -e port 20001 and src host 1.1.1.126 and not ether src 04:2c:0d:ba:10:6c"),
            stdout=subprocess.PIPE)

    def run(self):
        while True:
            result_list = self.process.stdout.readline().decode().split(" ")
            result = self.handler.handle(_result_list=result_list)
            if result["flag"] is True:
                # self.history.append(result["data"]) if result['data'] else None
                print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}: {result}") if result['data'] else None
            self._print_count = self.handler.print_count
            now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            print(f"{now}: Printed {self._print_count} pics since {self.start_time}")
            print(f"{now}: Total count: {self.total_count + self._print_count}")


if __name__ == '__main__':
    # 读取配置信息
    config = configparser.ConfigParser()
    config.read("configure.ini")
    organization = config.get("MachineInfo", "Organization")
    machine_name = config.get("MachineInfo", "MachineName")
    interface = config.get("Interface", "Interface")
    filter = config.get("Arguments", "Filter")
    total_count = config.getint("Status", "TotalCount")
    # 初始化信号处理器
    handler = HeidelbergHandler(organization=organization, machine_name=machine_name)
    capture = pyshark.LiveCapture(interface=interface, bpf_filter=filter)
    # capture = pyshark.LiveCapture(interface='MC2.5')
    # capture = pyshark.LiveCapture()
    # machine = SignalClass(machine_name, capture, handler)
    machine = Tcpdump(machine_name, capture, handler)
    machine.total_count = total_count
    machine.run()
